package com.nanako.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanako.common.R;
import com.nanako.dto.UserDto;
import com.nanako.entity.User;
import com.nanako.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 给用户发送验证码
     * @param map
     * @return
     */
    @PostMapping("/sendMsg")
    public R getCheckCode(@RequestBody Map map) {
        // 随机生成的验证码
        String checkCode = String.valueOf(RandomUtils.nextInt(100000, 999999));
        log.info("本次登录的验证码：{}",checkCode);
        //session.setAttribute(user.getPhone(), checkCode);
        redisTemplate.opsForValue().set(map.get("phone"), checkCode);
        return R.success("验证码发送成功");
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R login(@RequestBody UserDto userDto, HttpSession session) {
        // 从session中获取验证码
        //Object checkCode = session.getAttribute(userDto.getPhone());
        //session.removeAttribute("checkCode");
        // 从redis获取验证码
        Object checkCode = redisTemplate.opsForValue().get(userDto.getPhone());
        log.info("从session获取的验证码:checkCode = {}", checkCode);

        // 获取用户输入的验证码
        String inputCode = userDto.getCode();
        log.info("用户输入的验证码：inputCode = {}", inputCode);

        // 判断用户输入的验证码是否和redis中的验证码一致
        if (StringUtils.isNotEmpty(inputCode) && inputCode.equals(checkCode)) {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, userDto.getPhone());
            User user = userService.getOne(wrapper);
            // 判断，如果是新用户的话需要添加到数据库，如果不是新用户则直接登录
            if (ObjectUtils.isEmpty(user)){
                userService.save(userDto);
            }
            Long userDtoId = userDto.getId();
            Long realId = ObjectUtils.isNotEmpty(userDtoId) ? userDtoId : user.getId();
            session.setAttribute("userId", realId);
            // 清除redis验证码
            redisTemplate.delete(userDto.getPhone());
            return R.success("登录成功");
        }
        return R.error("登录失败");
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/loginout")
    public R loginout(HttpSession session) {
        session.removeAttribute("userId");
        return R.success("退出成功");
    }


}
